interface TouchEvent {
  touches: { clientX: number; clientY: number }[]
  changedTouches: { clientX: number; clientY: number }[]
}
const app = getApp()

let touchStartX: number = 0
let touchStartY: number = 0
let touchEndX: number = 0
let touchEndY: number = 0

Page({
  data: {
    cellArr: [] as number[][],
    isGameOver: false
  },
  onLoad: function () {
    this.startGame()
  },
  startGame() {
    this.setData({
      isGameOver: false,
      cellArr: [
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]
      ]
    }
    )
    this.fillOneEmptyCell()
    this.fillOneEmptyCell()
  },
  fillOneEmptyCell() {
    const emptyCells = this.findEmptyCells()
    const index = this.getRandomPos(emptyCells.length)
    const [row, col] = emptyCells[index]
    this.data.cellArr[row][col] = this.getRandomValue()
    this.setData({ cellArr: this.data.cellArr })
  },
  getRandomValue(): number {
    if (Math.random() < 0.9) {
      return 2
    } else {
      return 4
    }
  },
  getRandomPos(length: number) {
    return Math.floor(Math.random() * length)
  },
  findEmptyCells(): [number, number][] {
    const result: [number, number][] = []
    for (let i = 0; i < 4; i++) {
      for (let j = 0; j < 4; j++) {
        if (this.data.cellArr[i][j] === 0) {
          result.push([i, j])
        }
      }
    }
    return result
  },
  touchStart(event: TouchEvent) {
    const touch = event.touches[0]
    touchStartX = touch.clientX
    touchStartY = touch.clientY
    touchEndX = touch.clientX
    touchEndY = touch.clientY
  },
  touchMove(event: TouchEvent) {
    const touch = event.touches[0]
    touchEndX = touch.clientX
    touchEndY = touch.clientY
  },
  touchEnd() {
    const disX = touchEndX - touchStartX
    const absDisx = Math.abs(disX)
    const disY = touchEndY - touchStartY
    const absDisY = Math.abs(disY)

    if (absDisx > 10 || absDisY > 10) {
      if (absDisx > absDisY) {
        if (disX > 0) {
          this.move('right')
        } else {
          this.move('left')
        }
      } else {
        if (disY > 0) {
          this.move('down')
        } else {
          this.move('up')
        }
      }
    }
  },
  move(direction: string) {
    this.moveCells(direction)
    this.checkGameOverOrContinue()
  },
  moveCells(direction: string) {
    const isHorizontal = direction === 'left' || direction === 'right'
    const isForward = direction === 'left' || direction === 'up'

    for (let i = 0; i < 4; i++) {
      let cells: number[] = []
      if (isHorizontal) {
        cells = this.data.cellArr[i]
      } else {
        for (let j = 0; j < 4; j++) {
          cells.push(this.data.cellArr[j][i])
        }
      }
      const result = this.removeZerosAndAdd(cells, isForward)
      if (isHorizontal) {
        this.data.cellArr[i] = result
      } else {
        result.forEach((value, j) => (this.data.cellArr[j][i] = value))
      }
    }
    this.setData({ cellArr: this.data.cellArr })
  },
  removeZerosAndAdd(cells: number[], isForward: boolean): number[] {
    const nonZeroCells = cells.filter(x => x !== 0)
    const mergedCells = this.mergeCells(nonZeroCells, isForward)
    const result = [0, 0, 0, 0]
    if (isForward) {
      result.splice(0, mergedCells.length, ...mergedCells)
    } else {
      result.splice(4 - mergedCells.length, mergedCells.length, ...mergedCells)
    }
    return result
  },
  mergeCells(cells: number[], isForward: boolean): number[] {
    if (!isForward) {
      cells = cells.reverse()
    }
    let result: number[] = []
    let i = 0
    while (i < cells.length) {
      if (i < cells.length - 1 && cells[i] === cells[i + 1]) {
        result.push(cells[i] * 2)
        i += 2
      } else {
        result.push(cells[i])
        i += 1
      }
    }
    if (!isForward) {
      result = result.reverse()
    }
    return result
  },
  checkGameOverOrContinue() {
    if (this.canMove()) {
      this.fillOneEmptyCell()
    } else {
      this.setData({ isGameOver: true })
    }
  },
  canMove(): boolean {
    const cellArr = this.data.cellArr
    for (let i = 0; i < 4; i++) {
      for (let j = 0; j < 4; j++) {
        if (cellArr[i][j] === 0) {
          return true
        }
        if (j < 3 && cellArr[i][j] === cellArr[i][j + 1]) {
          return true
        }
        if (i < 3 && cellArr[i][j] === cellArr[i + 1][j]) {
          return true
        }
      }
    }
    return false
  }
})
